package com.wondertek.poms.dao.repo.es.impl;

import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.dao.po.PublishLog;
import com.wondertek.poms.dao.repo.ISystemConfigDao;
import com.wondertek.poms.dao.repo.es.IPublishLogESDao;
import com.wondertek.poms.dao.util.ESUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author chenjijiang
 * @description
 */
@Slf4j
@Component
public class PublishLogESDaoImpl implements IPublishLogESDao {
	@Autowired
	private ISystemConfigDao systemConfigDao;

	@Override
	public Long getCount(String prdConId, String conId, Date pubStartTime, Date pubEndTime, String pubStatus, String prdInfoId, String createUserName) {
		String index_name = StringUtil.null2Str(systemConfigDao.findByCkey("Index_PrdContDao"));
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("PublishLog").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();

		if (prdConId != null && !prdConId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(prdConId)));
		}

		if (conId != null && !conId.equals("")) {
			qb.must(QueryBuilders.termQuery("CONT_ID", StringUtil.nullToString(conId)));
		}
		if (createUserName != null && !createUserName.equals("")) {
			qb.must(QueryBuilders.termQuery("CREATE_USER_NAME", StringUtil.nullToString(createUserName)));
		}

		if (pubStartTime == null && pubEndTime == null) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -2);
			Date startDate = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, +3);
			Date endDate = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			qb.filter(QueryBuilders.rangeQuery("CREATE_DATE").from(sdf.format(startDate)).includeLower(true)
					.to(sdf.format(endDate)).includeUpper(true));
		}
		if (pubStartTime != null && pubEndTime != null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(pubStartTime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(pubEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.filter(QueryBuilders.rangeQuery("CREATE_DATE").from(st).includeLower(true).to(et).includeUpper(true));
		}
		if (pubStartTime != null && pubEndTime == null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(pubStartTime);
			qb.must(QueryBuilders.rangeQuery("CREATE_DATE").from(st).includeLower(true));
		}
		if (pubStartTime == null && pubEndTime != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(pubEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.must(QueryBuilders.rangeQuery("CREATE_DATE").to(et).includeUpper(true));
		}

		if (pubStatus != null && !pubStatus.equals("")) {
			qb.must(QueryBuilders.termQuery("PUB_STATUS", StringUtil.nullToInteger(pubStatus)));
		}
		if (prdInfoId != null && !prdInfoId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_INFO_ID", StringUtil.nullToLong(prdInfoId)));
		}

		builder.setQuery(qb);
		log.info("index_name:" + index_name + "=====Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();
		log.info("====hits.getTotalHits:====" + hits.getTotalHits());
		return hits.getTotalHits();
	}

	@Override
	public List<PublishLog> getPubsPage(int start, int limit, String prdConId, String conId, Date pubStartTime, Date pubEndTime, String pubStatus, String prdInfoId, String createUserName) {
		String index_name = StringUtil.null2Str(systemConfigDao.findByCkey("Index_PrdContDao"));
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("PublishLog").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();

		if (prdConId != null && !prdConId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(prdConId)));
		}

		if (conId != null && !conId.equals("")) {
			qb.must(QueryBuilders.termQuery("CONT_ID", StringUtil.nullToString(conId)));
		}
		if (createUserName != null && !createUserName.equals("")) {
			qb.must(QueryBuilders.termQuery("CREATE_USER_NAME", StringUtil.nullToString(createUserName)));
		}

		if (pubStartTime == null && pubEndTime == null) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -2);
			Date startDate = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, +3);
			Date endDate = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			qb.filter(QueryBuilders.rangeQuery("CREATE_DATE").from(sdf.format(startDate)).includeLower(true)
					.to(sdf.format(endDate)).includeUpper(true));
		}
		if (pubStartTime != null && pubEndTime != null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(pubStartTime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(pubEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.filter(QueryBuilders.rangeQuery("CREATE_DATE").from(st).includeLower(true).to(et).includeUpper(true));
		}
		if (pubStartTime != null && pubEndTime == null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(pubStartTime);
			qb.must(QueryBuilders.rangeQuery("CREATE_DATE").from(st).includeLower(true));
		}
		if (pubStartTime == null && pubEndTime != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(pubEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.must(QueryBuilders.rangeQuery("CREATE_DATE").to(et).includeUpper(true));
		}

		if (pubStatus != null && !pubStatus.equals("")) {
			qb.must(QueryBuilders.termQuery("PUB_STATUS", StringUtil.nullToInteger(pubStatus)));
		}
		if (prdInfoId != null && !prdInfoId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_INFO_ID", StringUtil.nullToLong(prdInfoId)));
		}

		builder.addSort(SortBuilders.fieldSort("ID").order(SortOrder.DESC));
		if (start == 0 && limit == 0) {
			builder.setQuery(qb);
		} else {
			builder.setQuery(qb).setFrom(start).setSize(limit);
		}

		log.info("=====GETLIST Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();

		List<PublishLog> result = new ArrayList<PublishLog>();
		for (SearchHit hit : hits.getHits()) {
			PublishLog log = new PublishLog();
			log.setId(StringUtil.nullToLong(hit.getSource().get("ID")));
			log.setContId(StringUtil.nullToLong(hit.getSource().get("CONT_ID")));
			log.setContName(StringUtil.nullToString(hit.getSource().get("CONT_NAME")));
			log.setCreateTime(StringUtil.nullToDate(hit.getSource().get("CREATE_DATE"), "yyyy-MM-dd'T'HH:mm:ss"));
			log.setCreateUserName(StringUtil.nullToString(hit.getSource().get("CREATE_USER_NAME")));
			log.setOprCode(StringUtil.nullToLong(hit.getSource().get("OPR_CODE")));
			log.setPrdContId(StringUtil.nullToLong(hit.getSource().get("PRD_CONT_ID")));
			log.setPrdInfoId(StringUtil.nullToLong(hit.getSource().get("PRD_INFO_ID")));
			log.setStatus(StringUtil.nullToInteger(hit.getSource().get("STATUS")));
			result.add(log);
		}
		return result;
	}
}
